package com.dianban.controller.nengliang;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dianban.base.ResultCode;
import com.dianban.base.ResultVo;
import com.dianban.config.redis.RedisConstant;
import com.dianban.config.redis.RedisUtil;
import com.dianban.controller.BaseController;
import com.dianban.entity.JwShoproArea;
import com.dianban.entity.JwStore;
import com.dianban.entity.User;
import com.dianban.service.JwShoproAreaService;
import com.dianban.service.JwStoreService;
import com.dianban.utils.CaculateDistanceUtil;
import com.dianban.utils.IpUtils;
import com.dianban.utils.TencentMapUtils;
import com.dianban.utils.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.gavaghan.geodesy.Ellipsoid;
import org.gavaghan.geodesy.GlobalCoordinates;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

@Api(value = "ApiStoreController", description = "门店控制器")
@RestController
@RequestMapping(value = "${interfacePath}/nengliang/store/")
public class ApiStoreController extends BaseController {

    private Logger logger = LoggerFactory.getLogger(ApiStoreController.class);

    @Value("${rongyaotuadmin.domain}")
    private String rongyaotuadminDomain;

    @Autowired
    private JwStoreService jwStoreService;
    @Autowired
    private JwShoproAreaService jwShoproAreaService;

    @ApiOperation(notes = "list", httpMethod = "GET", value = "获取所有门店")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "keyword", value = "关键字查询", required = false, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "type", value = "类型，不传查的是荣耀兔，传box表示有机饭盒", required = false, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ResultVo list(@RequestParam(value = "keyword", required = false, defaultValue = "") String keyword,
                         @RequestParam(value = "type", required = false, defaultValue = "") String type, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        List<JwStore> storeList = new ArrayList<>();
        try {
            String from = "";
            String ipAddr = IpUtils.getIpAddr(request);
            JSONObject location = TencentMapUtils.location(ipAddr);
            logger.info("当前ip地址：{}", location);
            if (location != null) {
                if (location.get("result") != null) {
                    JSONObject result = JSONObject.parseObject(String.valueOf(location.get("result")));
                    if (result != null) {
                        JSONObject _location = JSONObject.parseObject(String.valueOf(result.get("location")));
                        if (_location != null) {
                            from = _location.get("lng") + "," + _location.get("lat");
                            //from = _location.get("lat") + "," + _location.get("lng");
                        }
                    }
                }
            }
            logger.info("from:{}", from);
            GlobalCoordinates source = null;
            if (!StringUtils.isEmpty(from)) {
                source = new GlobalCoordinates(Double.valueOf(from.split(",")[1]), Double.valueOf(from.split(",")[0]));
            }
            if (StringUtils.isEmpty(type)) {
                // 增加门店经纬度周边排序
                storeList = jwStoreService.findList(keyword);
            } else if ("box".equalsIgnoreCase(type)) {
                storeList = jwStoreService.findListByType(keyword, type);
            }
            if (!CollectionUtils.isEmpty(storeList)) {
                for (JwStore jwStore : storeList) {
                    jwStore.setMatrix("0");
                    if (!StringUtils.isEmpty(jwStore.getImages())) {
                        jwStore.setImages(jwStore.getImages().replaceAll("/uploads/", rongyaotuadminDomain + "/uploads/"));
                    }
                    if (!StringUtils.isEmpty(from)) {
                        if (!StringUtils.isEmpty(jwStore.getLal())) {
                            //jwStore.setMatrix(JSONObject.toJSONString(TencentMapUtils.matrix(from, jwStore.getLal())));
                            GlobalCoordinates target = new GlobalCoordinates(Double.valueOf(jwStore.getLal().split(",")[1]), Double.valueOf(jwStore.getLal().split(",")[0]));
                            jwStore.setMatrix(String.valueOf(CaculateDistanceUtil.getDistanceMeter(source, target, Ellipsoid.Sphere)));
                            //JSONObject jsonObject = TencentMapUtils.baiduTranslate(jwStore.getLal().split(",")[1] + "," + jwStore.getLal().split(",")[0]);
                            //if (jsonObject != null) {
                            //    JSONObject matrix = TencentMapUtils.matrix(from, jsonObject.get("lat")+","+jsonObject.get("lng"));
                            //    if (matrix != null) {
                            //        if (matrix.get("distance") != null && !StringUtils.isEmpty(matrix.get("distance"))) {
                            //            jwStore.setMatrix(JSONObject.toJSONString(matrix.get("distance")));
                            //        }
                            //    }
                            //}
                        }
                    }
                }
            }
            storeList.sort((a, b) -> Double.valueOf(a.getMatrix()).intValue() - Double.valueOf(b.getMatrix()).intValue());
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "获取失败");
        }
        return ResultVo.success(storeList, "获取成功");
    }

    @ApiOperation(notes = "add", httpMethod = "POST", value = "门店入驻")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userToken", value = "用户token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "name", value = "门店名称", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "phone", value = "联系人", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "province", value = "省", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "city", value = "市", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "area", value = "区", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "address", value = "详细地址", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "point", value = "经纬度", required = true, paramType = "query", dataType = "string"),
    })
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public ResultVo add(String name, String phone, String province, String city, String area, String address, String point, HttpServletRequest request, HttpServletResponse response) {
        String userToken = request.getHeader(UserUtils.USER_TOKEN);
        String key = RedisConstant.USER_TOKEN_KEY + userToken;
        User user = (User) RedisUtil.get(key);
        if (user == null) {
            return ResultVo.error(ResultCode.ERROR, "请求头userToken过期");
        }
        try {
            // 查询省市区具体名称
//            JwShoproArea province = jwShoproAreaService.findById(provinceId);
//            if (province == null) {
//                return ResultVo.error(ResultCode.ERROR, "省id数据不对");
//            }
//            JwShoproArea city = jwShoproAreaService.findById(cityId);
//            if (city == null) {
//                return ResultVo.error(ResultCode.ERROR, "市id数据不对");
//            }
//            JwShoproArea area = jwShoproAreaService.findById(areaId);
//            if (area == null) {
//                return ResultVo.error(ResultCode.ERROR, "区id数据不对");
//            }
            List<JwStore> jwStoreList = jwStoreService.findByUserId(user.getId());
            if (!CollectionUtils.isEmpty(jwStoreList)) {
                return ResultVo.error(ResultCode.ERROR, "当前用户有待审核入驻的门店，请等待审核结果后再进行申请");
            }
            JwStore jwStore = new JwStore();
            jwStore.setUserId(user.getId());
            jwStore.setName(name);
            jwStore.setContact(phone);
            jwStore.setAddress(address);
            jwStore.setProvinceName(province);
            jwStore.setCityName(city);
            jwStore.setAreaName(area);
            jwStore.setLal(point);
            jwStore.setStatus(0);
            jwStoreService.insert(jwStore);
        } catch (Throwable e) {
            e.printStackTrace();
            return ResultVo.error(ResultCode.ERROR, "操作失败");
        }
        return ResultVo.success("", "操作成功");
    }

}
